package com.i8office.android.zhihuixinwu.ui.schedule;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;


import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseFragment;
import com.cyan.tools.base.RecyclerArrayAdapter;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.adapter.ScheduleAdapter;
import com.i8office.android.zhihuixinwu.event.RefreshCalendarEvent;
import com.i8office.android.zhihuixinwu.module.contract.CalendarContract;
import com.i8office.android.zhihuixinwu.module.presenter.ScheduleListPresenter;
import com.i8office.android.zhihuixinwu.ui.TitleItemDecoration;
import com.i8office.android.zhihuixinwu.widget.ItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

@ActivityFragmentInject(contentViewId = R.layout.fragment_schedule_list)
public class ScheduleListFragment extends BaseFragment<CalendarContract.ScheduleListPresenter> implements CalendarContract.ScheduleListView, ScheduleAdapter.OnOperateListener {
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mRefreshLayout;
    private ScheduleAdapter mAdapter;
    private Calendar mCalendar;

    public static ScheduleListFragment newInstance(boolean leaderSet) {
        Bundle args = new Bundle();
        args.putBoolean("leaderSet", leaderSet);
        ScheduleListFragment fragment = new ScheduleListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private String getWeek(int year, int month, int day) {
        mCalendar.set(year, month - 1, day);
        int week = mCalendar.get(Calendar.DAY_OF_WEEK);
        switch (week) {
            case Calendar.MONDAY:
                return "星期一";
            case Calendar.TUESDAY:
                return "星期二";
            case Calendar.WEDNESDAY:
                return "星期三";
            case Calendar.THURSDAY:
                return "星期四";
            case Calendar.FRIDAY:
                return "星期五";
            case Calendar.SATURDAY:
                return "星期六";
            default:
                return "星期日";
        }
    }

    @Override
    protected void initView(View view) {
        ButterKnife.bind(this, view);
        mCalendar = Calendar.getInstance();
//        NormalDecoration decoration = new NormalDecoration() {
//            @Override
//            public String getHeaderName(int pos) {
//                try {
//                    return mAdapter.getData().get(pos).getStartDateString();
//                } catch (Exception e) {
//                    KLog.e("position:" + pos);
//                    return null;
//                }
//            }
//        };
//        decoration.setOnDecorationHeadDraw(new NormalDecoration.OnDecorationHeadDraw() {
//            @Override
//            public View getHeaderView(int pos) {
//                if (pos > mAdapter.getData().size() - 1) {
//                    View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_schedule_title, null);
//                    view.findViewById(R.id.text).setVisibility(View.GONE);
//                    return view;
//                } else {
//                    View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_schedule_title, null);
//                    String date = mAdapter.getData().get(pos).getStartDateString();
//                    String[] strs = date.split("-");
//                    String title = date + "\t" + getWeek(Integer.parseInt(strs[0]), Integer.parseInt(strs[1]), Integer.parseInt(strs[2]));
//                    ((TextView) view.findViewById(R.id.text)).setText(title);
//                    view.findViewById(R.id.text).setVisibility(View.VISIBLE);
//                    return view;
//                }
//
//            }
//        });
        mRecyclerView.addItemDecoration(new TitleItemDecoration<EventItem>(getActivity()));
        mRecyclerView.addItemDecoration(new ItemDecoration(getActivity(), 1));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(mAdapter = new ScheduleAdapter(getActivity(), this));
        mAdapter.setMore(menhoo.com.i8officelibrary.R.layout.view_more, new RecyclerArrayAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (mAdapter.getData().size() > 0) {
                    EventItem item = mAdapter.getData().get(mAdapter.getData().size() - 1);
                    mPresenter.getScheduleList(item.getStartDateString(), 1, false);
                }

            }
        });
        mAdapter.setError(menhoo.com.i8officelibrary.R.layout.view_more_error).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter.resumeMore();
            }
        });
        mAdapter.setNoMore(menhoo.com.i8officelibrary.R.layout.view_nomore);

        mPresenter = new ScheduleListPresenter(this);
        mRefreshLayout.setColorSchemeColors(ContextCompat.getColor(getActivity(), menhoo.com.i8officelibrary.R.color.tab_top_bg));
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (mAdapter.getData().size() > 0) {
                    EventItem item = mAdapter.getData().get(0);
                    mPresenter.getScheduleList(item.getStartDateString(), -1, true);
                } else {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    mPresenter.getScheduleList(format.format(System.currentTimeMillis()), -1, false);
                }
            }
        });
        getData();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(RefreshCalendarEvent event) {
        getData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void getData() {
        if (mAdapter.getData().size() > 0) {
            mAdapter.clear();
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        mPresenter.getScheduleList(format.format(System.currentTimeMillis()), 1, false);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        mPresenter.getScheduleList(format.format(calendar.getTimeInMillis()), -1, true);

    }

    @Override
    public void showEventData(boolean isRefresh, List<EventItem> data) {
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                EventItem item = data.get(i);
                String date = item.getStartDateString();
                String[] strs = date.split("-");
                String title = getWeek(Integer.parseInt(strs[0]), Integer.parseInt(strs[1]), Integer.parseInt(strs[2])) + "\t" + date;
                item.setTag(title);
            }
        }
        if (isRefresh) {
            if (data != null && data.size() > 0) {
                for (int i = data.size() - 1; i >= 0; i--) {
                    mAdapter.getData().add(0, data.get(i));
                }
                mAdapter.notifyDataSetChanged();
            }
        } else {
            if (data != null && data.size() > 0) {
                mAdapter.addAll(data);
                if (data.size() < 10) {
                    mAdapter.stopMore();
                }
            } else {
                mAdapter.stopMore();
            }

        }
    }

    @Override
    public void deleteSuccess(EventItem item) {
        EventBus.getDefault().post(new RefreshCalendarEvent());
        int index = mAdapter.getData().indexOf(item);
        mAdapter.remove(item);
        mAdapter.notifyItemRemoved(index);
    }

    @Override
    public void showProgress() {
        mRefreshLayout.setRefreshing(true);
    }

    @Override
    public void hideProgress() {
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onDelete(EventItem eventItem) {
        mPresenter.removeEvent(eventItem);
    }

    @Override
    public void onClickItem(final EventItem eventItem) {
        if (eventItem.getCanEdit() == 0) {
            new MaterialDialog.Builder(getActivity())
                    .title(R.string.hint)
                    .autoDismiss(true)
                    .content(eventItem.getDesc())
                    .positiveText(R.string.modify)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            Intent intent = new Intent(getActivity(), AddLeaderEventActivity.class);
                            intent.putExtra("event", eventItem);
                            startActivity(intent);
                        }
                    })
                    .negativeColorRes(R.color.textcolor2)
                    .negativeText(R.string.cancel)
                    .show();

        } else {
            Intent intent = new Intent(getActivity(), AddEventActivity.class);
            intent.putExtra("event", eventItem);
            startActivity(intent);
        }
    }
}
